package org.example.demo.controller.userController;


import org.example.demo.dto.UpdateAvatarParam;
import org.example.demo.service.userService.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.example.demo.util.RequestUtil;
import cn.hutool.json.JSONUtil;

import java.math.BigDecimal;

@Controller
@RequestMapping(value = "/user")
public class UserLoginController {

    @Autowired
    private UserAccountService userAccountService;

    final String AppId = "wx629cff2d7ea29653";
    final String AppSecret = "bd7228e36eee46e8291b6996f8ab96ba";


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ResponseBody
    public Long login(String loginCode) {
        System.out.println(loginCode);
        RequestUtil ru = new RequestUtil();
        String res = ru.requestOpenId(loginCode, AppId, AppSecret);
        System.out.println(res);
        if (!res.isEmpty()) {
            String openid = JSONUtil.parseObj(res).get("openid").toString();
            if (!openid.isEmpty()) {
//                比对openid与数据库，如果有，返回；如果没有，执行用户注册
                return userAccountService.userLogin(openid);
            }
        }
        return 0L;
    }

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    @ResponseBody
    public String hello() {
        return "hello";
    }


    @RequestMapping(value = "/avatar", method = RequestMethod.POST)
    @ResponseBody
    public String updateAvatr(@RequestBody UpdateAvatarParam updateAvatarParam) {
        userAccountService.updateAvatar(updateAvatarParam);
        return "ok";
    }

    @RequestMapping(value = "/balance", method = RequestMethod.GET)
    @ResponseBody
    public BigDecimal getbalance(Long user_id) {
        return userAccountService.getBalance(user_id);
    }
}
